package org.xtense.rcp.editors.action;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.ui.actions.ActionGroup;
import org.xtense.rcp.editors.XmlEditor;
import org.xtense.rcp.editors.util.XmlEntry;
import org.xtense.rcp.util.ImagesContext;

public class AttributePopupActionGroup extends ActionGroup {
	private TreeViewer tv;
	private XmlEditor editor;

	private MenuManager menuManager;

	public AttributePopupActionGroup(XmlEditor editor, TreeViewer tv) {
		this.editor = editor;
		this.tv = tv;
		menuManager = new MenuManager();
		
		menuManager.add(new RemoveAction());
	}

	public void fillContextMenu() {
		Tree tree = tv.getTree();
		Menu menu = menuManager.createContextMenu(tree);

		tree.setMenu(menu);
	}

	public void dispose() {
		tv.getTree().setMenu(null);
		super.dispose();
	}
	
	private class RemoveAction extends Action {
		public RemoveAction() {
			setText("&Remove");
			setImageDescriptor(ImagesContext
					.getImageDescriptor(ImagesContext.Delete));
		}

		public void run() {
			XmlEntry entry = getSelected();
			entry.remove();
			editor.setDirty(true);
			tv.refresh();
			
			entry.getNode().detach();
		}
	}
	
	public XmlEntry getSelected() {
		IStructuredSelection selection = (IStructuredSelection) tv
				.getSelection();
		XmlEntry entry = (XmlEntry) selection.getFirstElement();
		return entry;
	}

}
